<template>
  <div class="code">
    <div>
      <Form :model="modelForm" :rules="rules" ref="addVsForm" :label-width="85">
        <Row :gutter="32" class="code-row-bg">
          <Col span="12">
            <Form-item prop="vsCode" :label="_$t('vsCode')">
              <Input
                v-model.trim="modelForm.vsCode"
                :maxlength="50"
                :disabled="canEdit"
              />
            </Form-item>
          </Col>
          <Col span="12">
            <Form-item prop="vsName" :label="_$t('vsName')">
              <Input v-model="modelForm.vsName"></Input>
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="32" class="code-row-bg">
          <Col span="12">
            <Form-item prop="vsType" :label="_$t('vsType')">
              <Select
                v-model="modelForm.vsType"
                :disabled="canEdit"
                @on-change="onVsTypeChange"
                clearable
              >
                <Option value="1" selected="selected">{{_$t('independent')}}</Option>
                <Option value="2">{{_$t('subordinate')}}</Option>
              </Select>
            </Form-item>
          </Col>
          <Col span="12">
            <Form-item prop="vsParentCode" :label="_$t('parentVs')">
              <div class="form-choice-wrap">
                <Input v-model="modelForm.vsParentName" disabled  clearable />
                <Button
                  v-if="yesOrNo"
                  @click.native="getParentVs()"
                  class="marginLfet"
                >{{ _$t('select') }}</Button>
              </div>
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="32" class="code-row-bg">
          <Col span="12">
            <Form-item prop="enabled" :label="$t('common.status')">
              <RadioGroup v-model="modelForm.enabled" size="small">
                <Radio label="1">{{this.$t("common.enable")}}</Radio>
                <Radio label="0">{{this.$t("common.disable")}}</Radio>
              </RadioGroup>
            </Form-item>
          </Col>
          <Col span="12">
            <Form-item prop="ownnerTenant" :label="_$t('ownnerTenant')">
              <Input v-model="modelForm.ownnerTenant" disabled  />
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="32" class="code-row-bg">
          <Col class="vsValueSource">
            <Form-item :label="_$t('vsValueSource')">
              <RadioGroup v-model="modelForm.vsValueSource" size="small">
                <Radio :label="1" :disabled="canEdit">{{_$t('valueSourceItem.system')}}</Radio>
                <Radio :label="2" :disabled="canEdit">{{_$t('valueSourceItem.scalable')}}</Radio>
                <Radio
                  v-if="!isRipples"
                  :label="3"
                  :disabled="canEdit"
                >{{_$t('valueSourceItem.custom')}}</Radio>
                <Radio
                  v-if="!isRipples"
                  :label="4"
                  :disabled="canEdit"
                >{{_$t('valueSourceItem.dynamic')}}</Radio>
              </RadioGroup>
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="32" class="code-row-bg" v-if="modelForm.vsValueSource == 4">
          <Col span="24">
            <Form-item prop="vsInvokeUrl" :label="_$t('vsInvokeUrl')">
              <Input v-model="modelForm.vsInvokeUrl"  />
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="32" class="code-row-bg" v-if="modelForm.vsValueSource == 4">
          <Col span="12">
            <Form-item prop="vsCodeProp" :label="_$t('vsCodeProp')">
              <Input v-model="modelForm.vsCodeProp"  />
            </Form-item>
          </Col>
          <Col span="12">
            <Form-item prop="vsNameProp" :label="_$t('vsNameProp')">
              <Input v-model="modelForm.vsNameProp"  />
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="32" class="code-row-bg">
          <Col span="24">
            <Form-item :label="_$t('vsDesc')">
              <Input type="textarea" :rows="4" v-model="modelForm.vsDescribe" ></Input>
            </Form-item>
          </Col>
        </Row>
      </Form>
    </div>
  </div>
</template>
<script>
import GetParentVs from "./GetParentVs.vue";
import role from "@lang/modules/role";
import valueSet from "@lang/modules/valueSet";
import { codeReg } from "@/const.js";

export default {
  components: {},
  props: {
    vsId: {
      type: String,
      default() {
        return "";
      }
    },
    isRipples: {
      type: Boolean,
      default() {
        return false;
      }
    },
    // version: [String, Number],
    adminProductId: {
      type: String,
      default() {
        return "";
      }
    },
    ownnerTenantCode: {
      type: String,
      default() {
        return "";
      }
    },
    ownnerTenantName: {
      type: String,
      default() {
        return "";
      }
    }
  },
  locales: {
    "zh-CN": {
      module: {
        role: role["zh-CN"],
        valueSet: valueSet["zh-CN"]
      }
    },
    "en-US": {
      module: {
        role: role["en-US"],
        valueSet: valueSet["en-US"]
      }
    }
  },
  data() {
    const validateVsCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this._$t("enterVsCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };
    const validateVsName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this._$t("enterVsName")));
      } else if (value.length > 100) {
        callback(new Error(this._$t("maxVsName")));
      }
      callback();
    };
    return {
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          // icon: "add",
          handle: this.saveAddOrUpdate,
          loading: false
        },
        {
          text: this.$t("common.close"),
          // theme: "primary",
          handle: () => {
            this.$emit("Close");
          }
        }
      ],
      yesOrNo: false,
      canEdit: false,
      modelForm: {
        vsCode: "",
        vsName: "",
        version: "",
        vsType: "1",
        vsParentCode: "",
        vsParentName: "",
        // productId: "",
        enabled: "1",
        // publicFlag: "0",
        vsValueSource: 2,
        vsInvokeUrl: "",
        vsCodeProp: "",
        vsNameProp: "",
        vsDescribe: "",
        ownnerTenant: ""
      },
      rules: {
        vsCode: [{ validator: validateVsCode, trigger: "blur", required: true }],
        vsName: [{ required: true, validator: validateVsName, trigger: "blur" }],
        vsType: [{ required: true, message: this._$t("enterVsType"), trigger: "blur" }],
        // enabled: [{ required: true, message: this._$t("enterStatus"), trigger: "blur" }],
        ownnerTenant: [{ required: true, message: this._$t("enterTenant"), trigger: "blur" }]
        // productId: [
        //   {
        //     required: true,
        //     message: "请选择所属产品",
        //     trigger: "blur"
        //   }
        // ]
      },
      productList: []
    };
  },
  computed: {},
  created: function() {
    this.initProduct();
    if (this.modelForm.vsType == "2" || this.vsId) {
      this.yesOrNo = true;
    }
    if (this.vsId) {
      $http.get(`${window.RPConfig.setting}/valueset/view?valueSetId=${this.vsId}`).then(response => {
        response = response.data;
        this.modelForm = Object.assign(response, {
          vsType: String(response.vsType),
          // productId: response.productCode || this.adminProductId,
          enabled: String(response.enabled),
          publicFlag: String(response.publicFlag),
          vsId: this.vsId,
          version: response.version,
          ownnerTenant: response.tenantName
        });

        this.$emit("SetTitle", this._$t("editVs"));
        this.canEdit = true;
        this.yesOrNo = false;
      });
    } else {
      this.$emit("SetTitle", this._$t("createVs"));
    }
    this.$emit("SetPageWidth", 700);
    this.$emit("SetPageActions", this.actions);
  },
  beforeMount: function() {},
  mounted: function() {},
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    _$t(key) {
      return this.$t(`module.valueSet.${key}`);
    },
    // 初始化所属产品
    initProduct() {
      $http.get(`${window.RPConfig.setting}/valueset/item/list?vsCode=RC_PRODUCT`).then(({ data }) => {
        this.productList = data;
      });

      // 新增时
      if (!this.vsId) {
        this.modelForm.productId = this.adminProductId;
        this.modelForm.ownnerTenant = this.ownnerTenantName;
        // this.modelForm.ownnerTenant = this.ownnerTenant;
      }
    },
    saveAddOrUpdate() {
      //值集类型为从属时，校验"值来源"是否为空
      if (this.modelForm.vsParentCode == "" && this.modelForm.vsType == "2" && !this.vsId) {
        this.$message.error({
          content: this._$t("enterParentVs"),
          duration: 3
        });
        return;
      }
      this.$refs["addVsForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;

          if (this.vsId) {
            $http
              .post(
                `${window.RPConfig.setting}/valueset/update`,
                Object.assign(this.modelForm, {
                  // productCode: this.modelForm.ownnerTenant,
                  id: this.vsId,
                  version: this.version
                })
              )
              .then(() => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this._$t("updateSuccess"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(err => {
                this.actions[0].loading = false;
              });
          } else {
            $http
              .post(
                `${window.RPConfig.setting}/valueset/add`,
                Object.assign(this.modelForm, {
                  productCode: this.ownnerTenantCode
                  // productCode: this.modelForm.ownnerTenant
                })
              )
              .then(() => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this._$t("createSuccess"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(err => {
                this.actions[0].loading = false;
              });
          }
        } else {
          this.$message.error({
            content: this._$t("formValidateFailed"),
            duration: 3
          });
        }
      });
    },
    getParentVs() {
      if (this.modelForm.vsType == "1") {
        return false;
        // this.$message.error({
        //   content: this._$t("indVsNoParentVs"),
        //   duration: 3
        // });
        return;
      }
      if (this.vsId) {
        this.$message.error({
          content: this._$t("parentVsNoEdit"),
          duration: 3
        });
        return;
      }
      new this.$pageModal(GetParentVs, {}, data => {
        if (!!data) {
          this.modelForm.vsParentCode = data.vsCode;
          this.modelForm.vsParentName = data.vsName;
          return;
        }
      });
    },
    cancel() {
      this.$emit("Close");
    },
    clearInput() {
      this.modelForm.vsParentCode = "";
      //   this.modelForm.vsName = "";
    },
    onVsTypeChange(id) {
      if (!this.vsId) {
        if (id == "2") {
          this.yesOrNo = true;
        } else {
          this.yesOrNo = false;
          this.clearInput();
        }
      }
    }
  },
  watch: {
    "modelForm.vsValueSource": {
      handler: function(item) {
        if (item == 4) {
          this.rules.vsInvokeUrl = [{ required: true, message: this._$t("enterInvokeUrl"), trigger: "blur" }];
          this.rules.vsCodeProp = [{ required: true, message: this._$t("enterCodeProp"), trigger: "blur" }];
          this.rules.vsNameProp = [{ required: true, message: this._$t("enterNameProp"), trigger: "blur" }];
        } else {
          delete this.rules.vsInvokeUrl;
          delete this.rules.vsCodeProp;
          delete this.rules.vsNameProp;
        }
      }
    }
  },
  directives: {}
};
</script>
<style lang="less">
.code {
  padding: 10px;
  .code-row-bg {
    .marginLfet {
      margin-left: 10px;
    }
    .vsValueSource {
      width: 100% !important;
    }
  }
}
</style>

